package com.kaili.basic.controller;

import com.baomidou.mybatisplus.plugins.Page;
import com.kaili.basic.pojo.dto.MdmEmployeeAddOrUpdateDto;
import com.kaili.basic.pojo.dto.MdmEmployeeQueryDto;
import com.kaili.basic.pojo.dto.MdmEmployeeUpdatePasswordDto;
import com.kaili.basic.service.IBaseEmployeeService;
import com.kaili.basic.version.ApiVersion;
import com.kaili.common.pojo.entity.BaseEmployee;
import com.kaili.common.exception.RestException;
import com.kaili.common.response.CommonStatus;
import com.kaili.common.response.RestStatus;
import com.kaili.common.util.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * Created by rzh on 18-5-8.
 */
@ApiVersion(1)
@RequestMapping("/{api_version}")
@RestController
@Api(tags = "员工管理", description = "员工管理相关API")
public class MdmEmployeeController {
    @Autowired
    private IBaseEmployeeService baseEmployeeService;

    private Logger logger = LoggerFactory.getLogger(MdmEmployeeController.class);


    @ApiOperation(value = "查询员工", notes = "分页查员工")
    @GetMapping("baseEmployee")
    public Page<BaseEmployee> getCompany(@ModelAttribute MdmEmployeeQueryDto mdmEmployeeQueryDto) throws RestException {
        BaseEmployee baseEmployee = new BaseEmployee();
        baseEmployee.setPage(mdmEmployeeQueryDto.getPage());
        baseEmployee.setPageSize(mdmEmployeeQueryDto.getPageSize());
        baseEmployee.setSiteId(mdmEmployeeQueryDto.getSiteId());
        baseEmployee.setRid(mdmEmployeeQueryDto.getRid());
        baseEmployee.setEmployeeName(mdmEmployeeQueryDto.getEmployeeName());
        baseEmployee.setEmployeeCode(mdmEmployeeQueryDto.getEmployeeCode());
        if (LoginDetailUtils.getSiteId() != 1)
            baseEmployee.setSiteId(LoginDetailUtils.getSiteId());
        return baseEmployeeService.selectByMap(new Page<BaseEmployee>(baseEmployee.getPage(), baseEmployee.getPageSize()), baseEmployee);
    }


    @ApiOperation(value = "导出员工", notes = "导出员工")
    @GetMapping("baseEmployeeExport")
    public void exportCompany(@ModelAttribute MdmEmployeeQueryDto mdmEmployeeQueryDto, HttpServletResponse response) throws RestException {
        BaseEmployee baseEmployee = new BaseEmployee();
        baseEmployee.setPage(mdmEmployeeQueryDto.getPage());
        baseEmployee.setPageSize(mdmEmployeeQueryDto.getPageSize());
        baseEmployee.setSiteId(mdmEmployeeQueryDto.getSiteId());
        baseEmployee.setRid(mdmEmployeeQueryDto.getRid());
        baseEmployee.setEmployeeName(mdmEmployeeQueryDto.getEmployeeName());
        baseEmployee.setEmployeeCode(mdmEmployeeQueryDto.getEmployeeCode());
        if (LoginDetailUtils.getSiteId() != 1)
            baseEmployee.setSiteId(LoginDetailUtils.getSiteId());
        try{
            ExcelUtil.exportExcel(baseEmployeeService.exportByMap(baseEmployee),"用户管理","用户管理",BaseEmployee.class,"用户管理"+UUIDUtil.getUUId()+".xls",response);
        }catch (RestException e){
            logger.error("用户管理导出异常"+e.getMessage());
        }
        ;
    }

    @ApiOperation(value = "查询员工", notes = "模糊查询员工")
    @GetMapping("baseEmployee/page/{par}")
    public Page<BaseEmployee> selectByPar(@PathVariable String par) throws RestException {
        Integer par1 = null;
        if (LoginDetailUtils.getSiteId() != 1)
            par1 = LoginDetailUtils.getSiteId();
        return baseEmployeeService.selectByPar(new Page<BaseEmployee>(0, 50), par, par1);
    }

    @ApiOperation(value = "查询员工", notes = "根据id查询员工")
    @GetMapping("baseEmployee/{id}")
    public BaseEmployee getById(@PathVariable Integer id) throws RestException {
        return baseEmployeeService.selectById(id);
    }

    @ApiOperation(value = "新增或修改", notes = "新增或修改员工")
    @PostMapping("baseEmployee")
    public RestStatus insertOrUpdate(@Validated @RequestBody MdmEmployeeAddOrUpdateDto mdmEmployeeAddOrUpdateDto) {
        BaseEmployee baseEmployee = new BaseEmployee();
        baseEmployee.setEmployeeCode(mdmEmployeeAddOrUpdateDto.getEmployeeCode());
        baseEmployee.setEmployeeName(mdmEmployeeAddOrUpdateDto.getEmployeeName());
        baseEmployee.setEmployeeRealName(mdmEmployeeAddOrUpdateDto.getEmployeeRealName());
        baseEmployee.setMail(mdmEmployeeAddOrUpdateDto.getMail());
        baseEmployee.setSiteId(mdmEmployeeAddOrUpdateDto.getDeptId());
        baseEmployee.setRid(mdmEmployeeAddOrUpdateDto.getRid());
        baseEmployee.setEmployeeType(mdmEmployeeAddOrUpdateDto.getEmployeeType());
        baseEmployee.setShipper(mdmEmployeeAddOrUpdateDto.getShipper());
        baseEmployee.setDepot(mdmEmployeeAddOrUpdateDto.getDepot());
        baseEmployee.setPhone(mdmEmployeeAddOrUpdateDto.getPhone());
        baseEmployee.setLandPhone(mdmEmployeeAddOrUpdateDto.getLandPhone());
        baseEmployee.setPassword(mdmEmployeeAddOrUpdateDto.getPassword());
        baseEmployee.setId(mdmEmployeeAddOrUpdateDto.getId());
        baseEmployee.setCompanyId(mdmEmployeeAddOrUpdateDto.getCompanyId());
        baseEmployee.setPinyin(PinYinUtil.toPinYin(baseEmployee.getEmployeeName()));
        baseEmployee.setRemark(mdmEmployeeAddOrUpdateDto.getRemark());
        if (baseEmployee.getPassword() != null && baseEmployee.getPassword().length() <= 10 && !"".equals(baseEmployee.getPassword())) {
            String pwd = baseEmployee.getPassword();//密码
            String npwd = baseEmployee.getPassword();//用来循环的密码；
            String encode = hexpwd(pwd, npwd);//加密后16进制的密码;
            baseEmployee.setPassword(encode);
        }
        if (baseEmployee.getId() != null) {
            baseEmployee.setSiteName(null);
            baseEmployee.setrName(null);
            baseEmployee.setCreatedName(null);
            baseEmployee.setModifyBy(LoginDetailUtils.getCurrentEmployeeId().longValue());
            baseEmployee.setModifyTime(new Date());
        } else {
            baseEmployee.setCreateBy(LoginDetailUtils.getCurrentEmployeeId().longValue());
            baseEmployee.setCreateTime(new Date());
            baseEmployee.setLoadTimes(0);
        }

        baseEmployeeService.insertOrUpdate(baseEmployee);


        if (baseEmployee.getId() != null) {
            return CommonStatus.UPDATE_OK;
        }
        return CommonStatus.ADD_OK;
    }

    //修改密码
    @ApiOperation(value = "修改密码", notes = "根据Id修改密码")
    @PutMapping("baseEmployee")
    public RestStatus updatePassword(@Validated @RequestBody MdmEmployeeUpdatePasswordDto mdmEmployeeUpdatePasswordDto) {
        Map<String,Object> params = new HashMap<String,Object>();
        if (mdmEmployeeUpdatePasswordDto.getPassword() != null && mdmEmployeeUpdatePasswordDto.getPassword().length() <= 10 && !"".equals(mdmEmployeeUpdatePasswordDto.getPassword())){
            String pwd = mdmEmployeeUpdatePasswordDto.getPassword();//密码
            String npwd = mdmEmployeeUpdatePasswordDto.getPassword();//用来循环的密码；
            String encode = hexpwd(pwd, npwd);//加密后16进制的密码;
            params.put("password",encode);
        }
        params.put("id",mdmEmployeeUpdatePasswordDto.getId());

        baseEmployeeService.updatePasswordById(params);
        return CommonStatus.UPDATE_OK;
    }

    @ApiOperation(value = "删除", notes = "根据Id删除员工")
    @DeleteMapping("baseEmployee/{id}")
    public RestStatus delete(@PathVariable Integer id) {
        baseEmployeeService.deleteById(id);
        return CommonStatus.DELETE_OK;
    }

//    @ApiOperation(value = "获取Code", notes = "获取员工Code")
//    @GetMapping("baseEmployee/code")
//    public Map getCode() throws RestException {
//        String siteCode = basicSiteService.getBySiteId(getById(LoginDetailUtils.getCurrentEmployeeId()).getSiteId().longValue()).getSiteCode();
//        String code = baseEmployeeService.getCode();
//        Map map = new HashMap();
//        map.put("siteCode", siteCode);
//        map.put("code", code);
//        return map;
//    }


    public String hexpwd(String pwd, String npwd) {
        String salt = UUID.randomUUID().toString().substring(0, 6);
        Random random = new Random();
        int cycletimes = (int) (random.nextInt(100)) + 100;//后随机数范围变成[ 100~999）；循环次数
        String sh256 = "";
        sh256 = SHA256Util.getSHA256StrJava("G1" + salt + pwd);//G1+随机数+密码进行SHA256运算 循环多少次循环的次数是随机生成的
        for (int i = 0; i <= cycletimes; i++) {
            sh256 = SHA256Util.getSHA256StrJava("G1" + salt + pwd + sh256);//G1+随机数+密码进行SHA256运算 循环多少次循环的次数是随机生成的
            sh256 = sh256;
            //sh256=SHA256Util.getSHA256StrJava("G1"+cd+"123456");
        }
        String hex = HexStringUtils.toHex("G1" + salt + cycletimes + sh256);//16进制字符串
        return hex;
    }



}
